import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Input, Select, Button, Pagination, Empty, Spin } from 'antd';
import { SearchOutlined, FilterOutlined, BookOutlined, StarOutlined, EyeOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { courseAPI } from '../../utils/api';
import './index.scss';

const { Search } = Input;
const { Option } = Select;

const Courses = () => {
  const navigate = useNavigate();
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(12);
  const [filters, setFilters] = useState({
    keyword: '',
    category: '',
    level: '',
    price: '',
    sort: 'latest',
  });

  useEffect(() => {
    fetchCourses();
  }, [current, pageSize, filters]);

  const fetchCourses = async () => {
    try {
      setLoading(true);
      const params = {
        page: current,
        limit: pageSize,
        ...filters,
      };
      
      const response = await courseAPI.getCourses(params);
      setCourses(response.data || []);
      setTotal(response.total || 0);
    } catch (error) {
      console.error('Failed to fetch courses:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value) => {
    setFilters(prev => ({ ...prev, keyword: value }));
    setCurrent(1);
  };

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
    setCurrent(1);
  };

  const handlePageChange = (page, size) => {
    setCurrent(page);
    setPageSize(size);
  };

  const renderCourseCard = (course) => (
    <Col xs={24} sm={12} md={8} lg={6} key={course.id}>
      <Card
        hoverable
        className="course-card"
        cover={
          <div className="course-cover">
            <img alt={course.title} src={course.cover_image} />
            <div className="course-overlay">
              <Button
                type="primary"
                size="small"
                onClick={() => navigate(`/courses/${course.id}`)}
              >
                查看详情
              </Button>
            </div>
          </div>
        }
        onClick={() => navigate(`/courses/${course.id}`)}
      >
        <Card.Meta
          title={course.title}
          description={
            <div>
              <p className="course-description">{course.description}</p>
              <div className="course-meta">
                <span>
                  <EyeOutlined /> {course.view_count}
                </span>
                <span>
                  <StarOutlined /> {course.rating}
                </span>
                <span>
                  <BookOutlined /> {course.lesson_count}课时
                </span>
              </div>
              <div className="course-price">
                <span className="price">¥{course.price}</span>
                {course.original_price && (
                  <span className="original-price">¥{course.original_price}</span>
                )}
              </div>
            </div>
          }
        />
      </Card>
    </Col>
  );

  return (
    <div className="courses-page">
      <div className="courses-header">
        <h1>课程中心</h1>
        <p>发现优质课程，提升专业技能</p>
      </div>

      <div className="courses-filters">
        <Row gutter={[16, 16]} align="middle">
          <Col xs={24} md={8}>
            <Search
              placeholder="搜索课程..."
              onSearch={handleSearch}
              size="large"
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col xs={12} md={3}>
            <Select
              placeholder="分类"
              value={filters.category}
              onChange={(value) => handleFilterChange('category', value)}
              size="large"
              style={{ width: '100%' }}
            >
              <Option value="">全部分类</Option>
              <Option value="programming">编程开发</Option>
              <Option value="design">设计创意</Option>
              <Option value="business">商业管理</Option>
              <Option value="language">语言学习</Option>
            </Select>
          </Col>
          <Col xs={12} md={3}>
            <Select
              placeholder="难度"
              value={filters.level}
              onChange={(value) => handleFilterChange('level', value)}
              size="large"
              style={{ width: '100%' }}
            >
              <Option value="">全部难度</Option>
              <Option value="beginner">初级</Option>
              <Option value="intermediate">中级</Option>
              <Option value="advanced">高级</Option>
            </Select>
          </Col>
          <Col xs={12} md={3}>
            <Select
              placeholder="价格"
              value={filters.price}
              onChange={(value) => handleFilterChange('price', value)}
              size="large"
              style={{ width: '100%' }}
            >
              <Option value="">全部价格</Option>
              <Option value="free">免费</Option>
              <Option value="paid">付费</Option>
            </Select>
          </Col>
          <Col xs={12} md={3}>
            <Select
              placeholder="排序"
              value={filters.sort}
              onChange={(value) => handleFilterChange('sort', value)}
              size="large"
              style={{ width: '100%' }}
            >
              <Option value="latest">最新</Option>
              <Option value="popular">最热</Option>
              <Option value="rating">评分</Option>
              <Option value="price_asc">价格从低到高</Option>
              <Option value="price_desc">价格从高到低</Option>
            </Select>
          </Col>
        </Row>
      </div>

      <div className="courses-content">
        {loading ? (
          <div className="loading-container">
            <Spin size="large" />
          </div>
        ) : courses.length > 0 ? (
          <>
            <Row gutter={[16, 16]}>
              {courses.map(renderCourseCard)}
            </Row>
            <div className="pagination-container">
              <Pagination
                current={current}
                total={total}
                pageSize={pageSize}
                showSizeChanger
                showQuickJumper
                showTotal={(total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                }
                onChange={handlePageChange}
                onShowSizeChange={handlePageChange}
              />
            </div>
          </>
        ) : (
          <Empty
            description="暂无课程"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        )}
      </div>
    </div>
  );
};

export default Courses; 